import {
  defineStore
} from "pinia";
import {
  reqLogout
} from '@/api/login.js'

import {
  constantRoute,
  asyncRoutr_admin,
  asyncRoutr_role,
} from '@/router/routes.js'
import router from "@/router/index";
import {
  scopy

} from '@/utils/common.js'

export default defineStore("login", {
  state: () => {
    return {
      token: localStorage.getItem('token'),
      luser: localStorage.getItem('luser'),
      image64: localStorage.getItem('image64'),
      usernaem: localStorage.getItem('usernaem'),
      menulist: constantRoute,
    };
  },
  actions: {
    // 用户登录
    async userLogin(login_data) {
      let result = await reqLogout(login_data)
      if (result.resultStatus.resultCode == '0000') {
        this.token = result.value.authorization
        this.image64 = result.value.image64 ? result.value.image64 : '0'
          this.usernaem =result.value.customerName?result.value.customerName:'阴极保护和腐蚀速率远程智能监控及预警云系统'
        this.luser = result.value
        localStorage.setItem('token', result.value.authorization)
        localStorage.setItem('luser', JSON.stringify(result.value))
        localStorage.setItem('usernaem',result.value.customerName?result.value.customerName:'阴极保护和腐蚀速率远程智能监控及预警云系统')
        localStorage.setItem('image64', result.value.image64?result.value.image64:'0')
        await this.router_fun()

        return 'ok'
      } else {
        return Promise.reject(new Error(result.resultStatus.resultMessage))
      }
    },
    router_fun() {
      let luser = JSON.parse(localStorage.getItem('luser'))
      console.log(luser.loginName, 'luser.loginName')
      if (luser.loginName == 'admin') {
        this.menulist = [...constantRoute, ...asyncRoutr_admin]
        // 注册异步路由和任意路由
        let arr_list = [...asyncRoutr_admin]
        arr_list.forEach((route) => {
          router.addRoute(route)
        })
      } else {
        this.menulist = [...constantRoute, ...asyncRoutr_role]
        // 注册异步路由和任意路由
        let arr_list = [...asyncRoutr_role]
        arr_list.forEach((route) => {
          router.addRoute(route)
        })
      }
    },

  },
  getters: {},
});
